(asdf:load-system :staple-markdown)

(defclass my-page (staple:simple-page) ())

(defmethod staple:page-type ((system (eql (asdf:find-system :cl-fast-ecs))))
  'my-page)

(defmethod staple:packages ((system (eql (asdf:find-system :cl-fast-ecs))))
  (mapcar #'find-package '(:cl-fast-ecs)))

(defmethod staple:format-documentation ((docstring string) (page my-page))
  (flet ((replace-see (string start end mstart mend rstart rend)
           (declare (ignore start end))
           (let* ((match (subseq string (aref rstart 0) (aref rend 0)))
                  (identifier (plump:decode-entities match))
                  xref)
             (cond ((cl-ppcre:scan "^[-a-zA-Z]+://" identifier)
                    (format NIL "See <a href=\"~a\" class=\"exref\">~a</a><br>"
                            match match))
                   ((setf xref (staple:xref identifier))
                    (format NIL "See <a href=\"~a\" class=\"xref\">~a</a><br>"
                            (plump:encode-entities xref) match))
                   (T
                    (subseq string mstart mend))))))
    (let* ((docstring (plump:encode-entities docstring))
           (docstring (cl-ppcre:regex-replace-all "[sS]ee (.*)" docstring
                                                  #'replace-see))
           (*package* (first (staple:packages page))))
      (staple:markup-code-snippets-ignoring-errors
       (staple:compile-source docstring :markdown)))))

(defmethod staple:xref :around ((identifier string) &optional (type T))
  "HACK"
  (if (find-symbol identifier :cl)
      (staple:xref
       (first
        (staple:find-definitions-for-identifier identifier
                                                :package :cl :type type))
       type)
      (call-next-method)))

(defmethod staple:template ((system (eql (asdf:find-system :cl-fast-ecs))))
  (asdf:system-relative-pathname system #p"docs/doc-template.ctml"))
